#!/bin/bash
#
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# This script starts Solr on localhost, creates a core with "solr create",
# stops Solr, and then starts Solr as normal.
# Any arguments are passed to the "solr create".
# To simply create a core:
#      docker run -P -d solr solr-create -c mycore
# To create a core from mounted config:
#      docker run -P -d -v $PWD/myconfig:/myconfig solr solr-create -c mycore -d /myconfig

set -euo pipefail
echo "Executing $0" "$@"

if [[ "${VERBOSE:-}" == "yes" ]]; then
    set -x
fi

# init script for handling an empty /var/solr
/opt/docker-solr/scripts/init-var-solr

. /opt/docker-solr/scripts/run-initdb

# solr uses "-c corename". Parse the arguments to determine the core name.
CORE_NAME="$(
  while (( $# > 0 )); do
    if [[ "$1" == '-c' ]]; then
      shift
      echo "$1"
    fi
    shift
  done
)"
if [[ -z "${CORE_NAME:-}" ]]; then
  echo "Could not determine core name"
  exit 1
fi

coresdir=/var/solr/data
CORE_DIR="$coresdir/$CORE_NAME"

if [[ -d $CORE_DIR ]]; then
    echo "Directory $CORE_DIR exists; skipping core creation"
else
    start-local-solr

    echo "Creating core with:" "${@:1}"
    /opt/solr/bin/solr create "${@:1}"

    # See https://github.com/docker-solr/docker-solr/issues/27
    echo "Checking core"
    if ! wget -O - "http://localhost:${SOLR_PORT:-8983}/solr/admin/cores?action=STATUS" | grep instanceDir >/dev/null; then
      echo "Could not find any cores"
      exit 1
    fi

    echo "Created core with:" "${@:1}"
    stop-local-solr

    # check the core_dir exists; otherwise the detecting above will fail after stop/start
    if [ ! -d "$CORE_DIR" ]; then
        echo "Missing $CORE_DIR"
        exit 1
    fi
fi

exec solr-fg
